package com.linln.modules.userule.rule;

import com.linln.modules.ticket.domain.Ticket;
import com.linln.modules.ticket.rule.Rule;
import com.linln.modules.ticket.rule.RuleResult;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.user.rule
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.user.rule
 * @Description: TODO
 * @date Date : 2020年11月25日 18:17
 */
@Component("compositeRule")
@Order(Integer.MIN_VALUE)
public class CompositeRule implements Rule {
    @Autowired
    private List<Rule> ruleList;

    private ThreadLocal<String> ruleId = new ThreadLocal<>();

    @Override
    public boolean support(String ruleId) {
        if (Strings.isBlank(ruleId)) {
            return false;
        }
        this.ruleId.set(ruleId);
        return true;
    }

    @Override
    public RuleResult handlerCode(String userId, Ticket ticket,String shopId) {
        for (Rule rule : ruleList) {
            if (rule.support(ruleId.get())) {
                RuleResult ruleResult = rule.handlerCode(userId, ticket,shopId);
                if (ruleResult != null) {
                    return ruleResult;
                }
            }
        }
        return RuleResult.error("无法处理这个券规则");
    }
}
